<?php

require_once('functions/pageLoad.php');

if(isset($_SESSION['user'])){
$user_session = explode("_", $_SESSION['user']);
}
// job info

$additionalMeta = '<link rel="stylesheet" type="text/css" href="/library/slimbox.css" media="screen" />
<script type="text/javascript" src="/library/mootools.js"></script>
<script type="text/javascript" src="/library/slimbox.js"></script>';

$sql = "SELECT jobs.user_id, title, description, addresses.longitude, addresses.latitude, jobs.status AS job_status, date_added, area, trade, jobs.quote_id, jobs.area_id, jobs.trade_id, materials 
	FROM jobs 
	LEFT JOIN addresses ON jobs.address_id = addresses.id 
	LEFT JOIN trades ON jobs.trade_id = trades.id 
	LEFT JOIN areas ON jobs.area_id = areas.id 
	WHERE jobs.id = '".mysql_real_escape_string($_GET['id'])."' LIMIT 0,1";
$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
$job_rs=mysql_fetch_assoc($query);

// image post

if($_SERVER['REQUEST_METHOD'] == 'POST'){

// HANDLE IMAGES

	require_once('functions/imageScale.php');

	$rootPath = $_SERVER['DOCUMENT_ROOT'].'/public_images/';

	if(isset($_FILES['image_1']['tmp_name']) && strlen($_FILES['image_1']['tmp_name']) > 0){

	$imageName = $_FILES['image_1']['tmp_name'];
	$newImageName = $user_id.'-'.mktime().'-1';

	//large dimensions
	$maxWidth = '700';
	$maxHeight = '466';
	$imgScale1a = imageScale($rootPath.'large/', $imageName, $newImageName, $maxWidth, $maxHeight);

	//small dimensions
	$maxWidth = '108';
	$maxHeight = '300';
	$imgScale1b = imageScale($rootPath.'small/', $imageName, $newImageName, $maxWidth, $maxHeight);

	if(strlen($imgScale1a['error']) == 0){
	// add image 1 to db

	$sql = "INSERT INTO images (string, job_id) VALUES ('".$imgScale1a['image']."', '".mysql_real_escape_string($_GET['id'])."')";
	$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
	$img1_id = mysql_insert_id();

	}

	}

	if(isset($_FILES['image_2']['tmp_name']) && strlen($_FILES['image_2']['tmp_name']) > 0){

	$imageName = $_FILES['image_2']['tmp_name'];
	$newImageName = $user_id.'-'.mktime().'-2';

	//large dimensions
	$maxWidth = '700';
	$maxHeight = '466';
	$imgScale2a = imageScale($rootPath.'large/', $imageName, $newImageName, $maxWidth, $maxHeight);

	//small dimensions
	$maxWidth = '108';
	$maxHeight = '300';
	$imgScale2b = imageScale($rootPath.'small/', $imageName, $newImageName, $maxWidth, $maxHeight);

	if(strlen($imgScale2a['error']) == 0){

	// add image 2 to db

	$sql = "INSERT INTO images (string, job_id) VALUES ('".$imgScale2a['image']."', '".mysql_real_escape_string($_GET['id'])."')";
	$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());

	}

	}

	if(isset($_FILES['image_3']['tmp_name']) && strlen($_FILES['image_3']['tmp_name']) > 0){

	$imageName = $_FILES['image_3']['tmp_name'];
	$newImageName = $user_id.'-'.mktime().'-3';

	//large dimensions
	$maxWidth = '700';
	$maxHeight = '466';
	$imgScale3a = imageScale($rootPath.'large/', $imageName, $newImageName, $maxWidth, $maxHeight);

	//small dimensions
	$maxWidth = '108';
	$maxHeight = '300';
	$imgScale3b = imageScale($rootPath.'small/', $imageName, $newImageName, $maxWidth, $maxHeight);

	if(strlen($imgScale3a['error']) == 0){

	// add image 3 to db

	$sql = "INSERT INTO images (string, job_id) VALUES ('".$imgScale3a['image']."', '".mysql_real_escape_string($_GET['id'])."')";
	$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());

	}

	}
	
	header("Location: ".$_SERVER['REQUEST_URI']);

}

// approved tradesman?
//Change By Vyas Ishan 24 May 2013 Task2 added the status field condition
$sql = "SELECT tradesman.id, radius, longitude, latitude FROM tradesman 
		LEFT JOIN subscriptions ON tradesman.subscription_id = subscriptions.id 
		LEFT JOIN addresses ON tradesman.address_id = addresses.id 
		LEFT JOIN tradesman_to_trade ON tradesman.id = tradesman_to_trade.tradesman_id 
		WHERE tradesman.user_id = '".$user_session[0]."' AND tradesman_to_trade.trade_id = '".$job_rs['trade_id']."' AND subscriptions.status = '1' AND tradesman.active = 1";

$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
$rows = mysql_num_rows($query);
$tradesman_id_rs=mysql_fetch_assoc($query);

$tradesman_id = $tradesman_id_rs['id'];
$approved_tradesman = ($rows > 0) ? 1 : 0;
$tradesman_radius = $tradesman_id_rs['radius'];

if($approved_tradesman == 1){

$in_tradesmans_area = (distance_calc($job_rs['latitude'], $job_rs['longitude'], $tradesman_id_rs['latitude'], $tradesman_id_rs['longitude'], 'm') <= $tradesman_id_rs['radius']) ? true : false ;

}

// visit request

if(isset($_GET['request_visit']) && $approved_tradesman == 1 && $in_tradesmans_area){

// check if already requested

$sql = "SELECT id FROM visit_requests WHERE job_id = '".mysql_real_escape_string($_GET['id'])."' AND tradesman_id = '".$tradesman_id."'";
$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
$visit_rows = mysql_num_rows($query);

	if($visit_rows > 0){
	// already requested
	$visit_results = '<p style="color: #cc0000;"><strong>You have already made a request to visit, please await a response.</strong></p>';
	}

	else{
	
	$sql = "INSERT INTO visit_requests SET job_id = '".mysql_real_escape_string($_GET['id'])."', tradesman_id = '".$tradesman_id."'";
	$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());

	// get users details

	$sql = "SELECT firstname, surname, email 
		FROM jobs
		LEFT JOIN users ON jobs.user_id = users.id
		LEFT JOIN addresses ON users.address_id = addresses.id 
		LEFT JOIN areas ON addresses.area_id = areas.id 
		WHERE jobs.id = '".mysql_real_escape_string($_GET['id'])."'";
	$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
	$user_details_for_visit_rs=mysql_fetch_assoc($query);

	// send email
	
	$job_link = build_job_link($job_rs['trade'],$job_rs['area'],$_GET['id']);
	
	require_once("classes/class.phpmailer.php");
	$mail = new PHPMailer();
	$mail->IsSMTP(); // telling the class to use SMTP
	$mail->Host = "localhost"; // SMTP server
	$mail->From = "mail@iwantatradesman.co.uk";
	$mail->FromName = "I Want A Tradesman";

	$mail->AddAddress($user_details_for_visit_rs['email']);

	$mail->Subject = "Visit request";
	$mail->Body = "Dear ".$user_details_for_visit_rs['firstname']." ".$user_details_for_visit_rs['surname']."\r\n\r\nA tradesman has requested to visit your property to enable them to provide a more accurate quotation.\r\n\r\nYou can choose to accept the visit request here: http://www.iwantatradesman.co.uk".$job_link."\r\n\r\nKind regards\r\n\r\nThe I Want A Tradesman Team\r\n\r\n\r\nThis email and any files transmitted with it are confidential and intended solely for the use of the individual or entity to whom they are addressed. This message contains confidential information and is intended only for the individual named. If you are not the named addressee you should not disseminate, distribute or copy this e-mail. Please notify the sender immediately by e-mail if you have received this e-mail by mistake and delete this e-mail from your system. If you are not the intended recipient you are notified that disclosing, copying, distributing or taking any action in reliance on the contents of this information is strictly prohibited.";

	$mail->Send();
	
	$visit_results = '<p style="color: #009900;"><strong>Your visit request has been made, please wait for the job owner to respond.</strong></p>';

	}

}

// accept request

if(isset($_GET['accept_request']) && $user_session[0] == $job_rs['user_id']){

	$sql = "UPDATE visit_requests SET accepted = '1' WHERE id = '".mysql_real_escape_string($_GET['accept_request'])."' AND job_id = '".mysql_real_escape_string($_GET['id'])."'";
	$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
	
	// tradesman id 
	$sql = "SELECT tradesman_id FROM visit_requests WHERE id = '".mysql_real_escape_string($_GET['accept_request'])."' AND job_id = '".mysql_real_escape_string($_GET['id'])."'";
	$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
	$tradesman_id_for_visit=mysql_fetch_assoc($query);
	
	// send email to tradesman
	$sql = "SELECT company_name, email FROM tradesman LEFT JOIN users ON tradesman.user_id = users.id WHERE tradesman.id = '".$tradesman_id_for_visit['tradesman_id']."'";
	$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
	$details_for_visit_rs=mysql_fetch_assoc($query);
	
	$job_link = build_job_link($job_rs['trade'],$job_rs['area'],$_GET['id']);
	
	require_once("classes/class.phpmailer.php");
	$mail = new PHPMailer();
	$mail->IsSMTP(); // telling the class to use SMTP
	$mail->Host = "localhost"; // SMTP server
	$mail->From = "mail@iwantatradesman.co.uk";
	$mail->FromName = "I Want A Tradesman";

	$mail->AddAddress($details_for_visit_rs['email']);

	$mail->Subject = "Visit request accepted";
	$mail->Body = "Dear ".$details_for_visit_rs['company_name']."\r\n\r\nThe owner of \"".$job_rs['title']."\" has accepted your visit request. Please visit the following URL to view their contact and address details: http://www.iwantatradesman.co.uk".$job_link."\r\n\r\nKind regards\r\n\r\nThe I Want A Tradesman Team\r\n\r\n\r\nThis email and any files transmitted with it are confidential and intended solely for the use of the individual or entity to whom they are addressed. This message contains confidential information and is intended only for the individual named. If you are not the named addressee you should not disseminate, distribute or copy this e-mail. Please notify the sender immediately by e-mail if you have received this e-mail by mistake and delete this e-mail from your system. If you are not the intended recipient you are notified that disclosing, copying, distributing or taking any action in reliance on the contents of this information is strictly prohibited.";

	$mail->Send();
	
	header("Location: ".$job_link);
	
}

// accepted request?

	$sql = "SELECT id FROM visit_requests WHERE job_id = '".mysql_real_escape_string($_GET['id'])."' AND tradesman_id = '".$tradesman_id."' AND accepted = '1'";
	$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
	$visit_rows=mysql_num_rows($query);
	$accepted_visit = ($visit_rows > 0) ? '1' : '0' ;
	
// accepted lead ?

	$sql = "SELECT id FROM lead_purchases WHERE job_id = '".mysql_real_escape_string($_GET['id'])."' AND tradesman_id = '".$tradesman_id."' AND accepted = '1'";
	$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
	$lead_rows=mysql_num_rows($query);
	$accepted_lead = ($lead_rows > 0) ? '1' : '0' ;
	
// accept lead purchase

if(isset($_GET['accept_details_request']) && $user_session[0] == $job_rs['user_id']){

// get cost andf transaction id

	$sql = "SELECT lead_cost, payment_ref FROM lead_purchases 
			LEFT JOIN jobs ON lead_purchases.job_id = jobs.id 
			LEFT JOIN trades ON jobs.trade_id = trades.id 
			WHERE lead_purchases.id = '".mysql_real_escape_string($_GET['accept_details_request'])."' AND lead_purchases.job_id = '".mysql_real_escape_string($_GET['id'])."'";
	$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
	$lead_details=mysql_fetch_assoc($query);

include "class.paypal.php";
$obj=new paypal_recurring;

$obj->paymentAmount = urlencode($lead_details['lead_cost']);

$obj->environment = 'live';	// or 'beta-sandbox' or 'live'
$obj->currencyID = urlencode('GBP');			// or other currency code ('GBP', 'EUR', 'JPY', 'CAD', 'AUD')
$obj->API_UserName = urlencode($settings['paypal_api_username']);
$obj->API_Password = urlencode($settings['paypal_api_password']);
$obj->API_Signature = urlencode($settings['paypal_api_signature']);
$obj->API_Endpoint = "https://api-3t.paypal.com/nvp";


	if($obj->doCapture($lead_details['payment_ref']) == 'success'){

	// update row
	$sql = "UPDATE lead_purchases SET accepted = 1 WHERE job_id = '".mysql_real_escape_string($_GET['id'])."' AND id = '".mysql_real_escape_string($_GET['accept_details_request'])."'";
	$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
	
	// notify tradesman
	
	$sql = "SELECT company_name, email FROM lead_purchases 
			LEFT JOIN tradesman ON lead_purchases.tradesman_id = tradesman.id 
			LEFT JOIN users ON tradesman.user_id = users.id 
			WHERE lead_purchases.id = '".mysql_real_escape_string($_GET['accept_details_request'])."' AND job_id = '".mysql_real_escape_string($_GET['id'])."'";
	$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
	$details_for_lead_rs=mysql_fetch_assoc($query);
	
	$job_link = build_job_link($job_rs['trade'],$job_rs['area'],$_GET['id']);
	
	require_once("classes/class.phpmailer.php");
	$mail = new PHPMailer();
	$mail->IsSMTP(); // telling the class to use SMTP
	$mail->Host = "localhost"; // SMTP server
	$mail->From = "mail@iwantatradesman.co.uk";
	$mail->FromName = "I Want A Tradesman";

	$mail->AddAddress($details_for_lead_rs['email']);

	$mail->Subject = "Lead purchase accepted";
	$mail->Body = "Dear ".$details_for_lead_rs['company_name']."\r\n\r\nThe owner of \"".$job_rs['title']."\" has accepted your lead purchase request. Please visit the following URL to view their contact details: http://www.iwantatradesman.co.uk".$job_link."\r\n\r\nKind regards\r\n\r\nThe I Want A Tradesman Team\r\n\r\n\r\nThis email and any files transmitted with it are confidential and intended solely for the use of the individual or entity to whom they are addressed. This message contains confidential information and is intended only for the individual named. If you are not the named addressee you should not disseminate, distribute or copy this e-mail. Please notify the sender immediately by e-mail if you have received this e-mail by mistake and delete this e-mail from your system. If you are not the intended recipient you are notified that disclosing, copying, distributing or taking any action in reliance on the contents of this information is strictly prohibited.";

	$mail->Send();
	
	header("Location: ".$job_link);

	}

}

// decline lead purchase

if(isset($_GET['decline_details_request']) && $user_session[0] == $job_rs['user_id']){

// get cost andf transaction id

	$sql = "SELECT payment_ref FROM lead_purchases 
			LEFT JOIN jobs ON lead_purchases.job_id = jobs.id 
			LEFT JOIN trades ON jobs.trade_id = trades.id 
			WHERE lead_purchases.id = '".mysql_real_escape_string($_GET['decline_details_request'])."' AND lead_purchases.job_id = '".mysql_real_escape_string($_GET['id'])."'";
	$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
	$lead_details=mysql_fetch_assoc($query);

include "class.paypal.php";
$obj=new paypal_recurring;

$obj->environment = 'live';	// or 'beta-sandbox' or 'live'
$obj->currencyID = urlencode('GBP');			// or other currency code ('GBP', 'EUR', 'JPY', 'CAD', 'AUD')
$obj->API_UserName = urlencode($settings['paypal_api_username']);
$obj->API_Password = urlencode($settings['paypal_api_password']);
$obj->API_Signature = urlencode($settings['paypal_api_signature']);
$obj->API_Endpoint = "https://api-3t.paypal.com/nvp";


	if($obj->doVoid($lead_details['payment_ref']) == 'success'){

	// update row
	$sql = "UPDATE lead_purchases SET declined = 1 WHERE job_id = '".mysql_real_escape_string($_GET['id'])."' AND id = '".mysql_real_escape_string($_GET['decline_details_request'])."'";
	$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
	
	// notify tradesman
	
	$sql = "SELECT company_name, email FROM lead_purchases 
			LEFT JOIN tradesman ON lead_purchases.tradesman_id = tradesman.id 
			LEFT JOIN users ON tradesman.user_id = users.id 
			WHERE lead_purchases.id = '".mysql_real_escape_string($_GET['decline_details_request'])."' AND job_id = '".mysql_real_escape_string($_GET['id'])."'";
	$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
	$details_for_lead_rs=mysql_fetch_assoc($query);
	
	$job_link = build_job_link($job_rs['trade'],$job_rs['area'],$_GET['id']);
	
	require_once("classes/class.phpmailer.php");
	$mail = new PHPMailer();
	$mail->IsSMTP(); // telling the class to use SMTP
	$mail->Host = "localhost"; // SMTP server
	$mail->From = "mail@iwantatradesman.co.uk";
	$mail->FromName = "I Want A Tradesman";

	$mail->AddAddress($details_for_lead_rs['email']);

	$mail->Subject = "Lead purchase declined";
	$mail->Body = "Dear ".$details_for_lead_rs['company_name']."\r\n\r\nUnfortunately the owner of \"".$job_rs['title']."\" has declined your lead purchase request. You can still quote the normal way by signing in and visting the job URL: http://www.iwantatradesman.co.uk".$job_link."\r\n\r\nKind regards\r\n\r\nThe I Want A Tradesman Team\r\n\r\n\r\nThis email and any files transmitted with it are confidential and intended solely for the use of the individual or entity to whom they are addressed. This message contains confidential information and is intended only for the individual named. If you are not the named addressee you should not disseminate, distribute or copy this e-mail. Please notify the sender immediately by e-mail if you have received this e-mail by mistake and delete this e-mail from your system. If you are not the intended recipient you are notified that disclosing, copying, distributing or taking any action in reliance on the contents of this information is strictly prohibited.";

	$mail->Send();
	
	header("Location: ".$job_link);

	}


}
	
	
// job images

$sql = "SELECT string, caption FROM images 
	WHERE job_id = '".mysql_real_escape_string($_GET['id'])."' LIMIT 0,3";
$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
$img_rows = mysql_num_rows($query);

if($img_rows > 0){
$job_images.='<div class="clear"></div>';
}

if($img_rows > 1){
$pp_gal = '[pp_gal]';
}


$image_i = 1;

while($image_rs=mysql_fetch_assoc($query)){
$image_class = ($image_i < 3) ? ' class="job_image"' : '' ;
$job_images.='<a href="/public_images/large/'.$image_rs['string'].'" rel="prettyPhoto'.$pp_gal.'" title="'.$image_rs['caption'].'"'.$image_class.'><img src="/public_images/small/'.$image_rs['string'].'" alt="" /></a>';
$image_i++;
}

$additionalMeta.='
<script type="text/javascript">
window.addEvent(\'domready\', function() {';

// user contact details?

if(strlen($job_rs['quote_id']) > 0 || $accepted_visit == '1' || $accepted_lead == '1'){

$sql = "SELECT quotes.id FROM quotes 
	LEFT JOIN reviews ON quotes.job_id = reviews.job_id 
	WHERE quotes.id='".$job_rs['quote_id']."' AND quotes.tradesman_id = '".$tradesman_id."' AND quotes.job_id = '".mysql_real_escape_string($_GET['id'])."' AND quotes.status = 'Accepted' AND reviews.id IS NULL";
$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
$accepted_quote = mysql_num_rows($query);

if($accepted_quote == '1' || $accepted_visit == '1' || $accepted_lead == '1'){

// show user details

$sql = "SELECT firstname, surname, email, telephone, mobile, users.address_id AS user_address_id, jobs.address_id AS job_address_id, line_1, line_2, line_3, area, postcode
	FROM jobs
	LEFT JOIN users ON jobs.user_id = users.id
	LEFT JOIN addresses ON users.address_id = addresses.id 
	LEFT JOIN areas ON addresses.area_id = areas.id 
	WHERE jobs.id = '".mysql_real_escape_string($_GET['id'])."'";
$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
$user_details_rs=mysql_fetch_assoc($query);

$user_contact_details = '
<div class="tradesman_info_wrap" style="margin-top: 10px; display: inline;">
<div class="tradesman_info_left">Name:</div>
<div class="tradesman_info_right">'.ucfirst($user_details_rs['firstname']).' '.ucfirst($user_details_rs['surname']).'</div>
</div>';

if($accepted_quote == '1' || $accepted_visit == '1'){

$user_contact_details.='<div class="tradesman_info_wrap">
<div class="tradesman_info_left">Email:</div>
<div class="tradesman_info_right"><a href="mailto:'.$user_details_rs['email'].'">'.$user_details_rs['email'].'</a></div>
</div>';

}

$user_contact_details.='<div class="tradesman_info_wrap">
<div class="tradesman_info_left">Telephone:</div>
<div class="tradesman_info_right">'.$user_details_rs['telephone'].'</div>
</div>';

if(strlen($user_details_rs['mobile']) > 0){

$user_contact_details.= '<div class="tradesman_info_wrap">
<div class="tradesman_info_left">Mobile:</div>
<div class="tradesman_info_right">'.$user_details_rs['mobile'].'</div>
</div>';

}

if($accepted_quote == '1' || $accepted_visit == '1'){

$user_contact_details.= '<div class="tradesman_info_wrap">
<div class="tradesman_info_left">Address:</div>
<div class="tradesman_info_right">'.$user_details_rs['line_1'].',';

$user_contact_details.=(strlen($user_details_rs['line_2']) > 0) ? '<br />'.$user_details_rs['line_2'].',' : '' ;
$user_contact_details.=(strlen($user_details_rs['line_3']) > 0) ? '<br />'.$user_details_rs['line_3'].',' : '' ;

$user_contact_details.= '<br />'.$user_details_rs['area'].'<br />'.strtoupper($user_details_rs['postcode']).'</div>
</div>';

if($user_details_rs['user_address_id'] != $user_details_rs['job_address_id']){

$sql = "SELECT line_1, line_2, line_3, area, postcode
	FROM jobs
	LEFT JOIN addresses ON jobs.address_id = addresses.id 
	LEFT JOIN areas ON addresses.area_id = areas.id 
	WHERE jobs.id = '".mysql_real_escape_string($_GET['id'])."'";
$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
$user_details_rs=mysql_fetch_assoc($query);

$user_contact_details.= '<div class="tradesman_info_wrap">
<div class="tradesman_info_left">Job location:</div>
<div class="tradesman_info_right">'.$user_details_rs['line_1'].',';

$user_contact_details.=(strlen($user_details_rs['line_2']) > 0) ? '<br />'.$user_details_rs['line_2'].',' : '' ;
$user_contact_details.=(strlen($user_details_rs['line_3']) > 0) ? '<br />'.$user_details_rs['line_3'].',' : '' ;

$user_contact_details.= '<br />'.$user_details_rs['area'].'<br />'.strtoupper($user_details_rs['postcode']).'</div>
</div>';

}

}

}

}

// quotes

$sql = "SELECT quotes.id, quote, username, company_name, tradesman_id, materials, info, status FROM quotes 
	LEFT JOIN tradesman ON quotes.tradesman_id = tradesman.id 
	WHERE job_id = '".mysql_real_escape_string($_GET['id'])."' ORDER BY date_quoted";
$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
$rows = mysql_num_rows($query);

$job_quotes = '<h2 id="quotes_header" style="margin-bottom: 10px;">Quotes</h2>';

if($rows > 0){

$i = 1;

$job_quotes.='<table width="100%" class="standard">';

while($quote_rs=mysql_fetch_assoc($query)){

$highlight = (is_int($i / 2)) ? ' class="highlight"' : '';

$average_feedback = tradesman_average_feedback($quote_rs['tradesman_id']);
$tradesman_link = build_tradesman_link($quote_rs['company_name'], $quote_rs['tradesman_id']);
$quote_amount = ($user_session[0] == $job_rs['user_id'] || $quote_rs['tradesman_id'] == $tradesman_id) ? '&pound;'.$quote_rs['quote'] : '--' ;

if($job_rs['quote_id'] != '0' && strlen($job_rs['quote_id']) > 0){
$quote_status = ($job_rs['quote_id'] == $quote_rs['id']) ? '<span style="color: #009900;">Accepted</span>' : '' ;
}

else{
if($user_session[0] == $job_rs['user_id'] && $job_rs['job_status'] != 'Closed'){
$quote_status = '<a onclick="return acceptQuote('.$quote_rs['id'].', \''.$quote_amount.'\', \''.ucfirst($quote_rs['company_name']).'\');" style="cursor: pointer; text-decoration: underline; color: #009900;">Accept quote</a>';
}
}

$contact_tradesman = ($user_session[0] == $job_rs['user_id']) ? '<a onclick="return send_message(\''.$quote_rs['tradesman_id'].'\',\''.$_GET['id'].'\');" style="cursor: pointer; text-decoration: underline;">Ask a question</a>' : '--';

$quote_status = (strlen($quote_status) == 0) ? '--' : $quote_status;

$materials = ($quote_rs['materials'] == '1') ? '<span style="color: #009900;">INCLUDED</span>' : '<span style="color: #cc0000;">NOT INCLUDED</span>';

$job_quotes.='<tr'.$highlight.'><td class="alignLeft"><a href="'.$tradesman_link.'"><strong>'.ucfirst($quote_rs['company_name']).'</strong></a></td><td>'.$quote_amount.'</td><td>Materials: '.$materials.'</td><td><img src="/images/'.$average_feedback.'-star.gif" alt="'.($average_feedback / 2).'/5" /><br /><a href="'.$tradesman_link.'">Feedback rating</a></td><td>'.$quote_status.'</td><td>'.$contact_tradesman.'</td></tr>';

if(($user_session[0] == $job_rs['user_id'] && strlen($quote_rs['info']) > 0) || $quote_rs['tradesman_id'] == $tradesman_id){
$job_quotes.='<tr id="quotes_details_'.$i.'"'.$highlight.'><td colspan="6" class="alignLeft">'.ucfirst($quote_rs['info']).'</td></tr>';
}

$i++;

}

$job_quotes.='</table>';

}

else{

$job_quotes.='<p>There are currently no quotes for this job.</p>';

}

// submit quote

$sql = "SELECT id FROM quotes WHERE job_id = '".mysql_real_escape_string($_GET['id'])."' AND tradesman_id = '".$tradesman_id."'";
$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
$tradesman_quoted=(mysql_num_rows($query) > 0) ? 1 : 0 ;

$sql = "SELECT id FROM jobs
	WHERE user_id = '".$user_session[0]."' AND jobs.id = '".mysql_real_escape_string($_GET['id'])."'";
$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
$same_tradesman=(mysql_num_rows($query) > 0) ? 1 : 0 ;

$job_quotes.=$visit_results;

if($approved_tradesman == 1 && $tradesman_quoted != 1 && $same_tradesman != 1 && $in_tradesmans_area){

$job_quotes.='<form method="post" action="/post_quote.php"><input type="hidden" name="jid" value="'.$_GET['id'].'" /><div><a style="cursor: pointer; text-decoration: underline;" id="loadQuoteForm" class="blue_link" onclick="document.getElementById(\'quote\').focus();">Submit quote</a><a href="?request_visit=true" class="blue_link" style="margin-left: 15px;">Request a visit</a></div>
<div id="submitQuote" style="float: left; width: 100%; padding-top: 5px;">
<div style="float: left; width: 100%; padding-top: 5px;">

<div id="quote_col_left">

<div class="formRowWrapper">
<div class="formRowLeft" style="width: 100px;"><label for="quote">Quote:</label></div>
<div class="formRowRight" style="width: 160px;"><span style="font-size: 11px; font-weight: bold; margin-right: 5px;">&pound;</span><input type="text" name="quote" id="quote" class="textbox currency" /></div>
</div>

<div class="formRowWrapper">
<div class="formRowLeft" style="width: 100px;"><label for="materials_yes">Includes materials:</label></div>
<div class="formRowRight" style="width: 160px;"><input type="radio" name="materials" id="materials_yes" value="1" checked="checked" /> <label for="materials_yes">Yes</label><br />
<input type="radio" name="materials" value="0" id="materials_no" /> <label for="materials_no">No</label></div>
</div>

</div><div id="quote_col_right">
<div class="formRowWrapper">
<div class="formRowLeft" style="width: 80px;"><label for="additional_info">Additional info: </label></div>
<div class="formRowRight" style="width: 260px;"><textarea name="additional_info" id="additional_info" rows="5" cols="33" class="textbox"></textarea></div>
</div>

<div class="formRowWrapper">
<div class="formRowLeft" style="width: 80px;">&nbsp;</div>
<div class="formRowRight" style="width: 260px;"><input type="image" src="/images/submit_quote.gif" alt="Submit quote" style="float: left; margin-left: 162px; display: inline;" /></div></div>
</div>


</div>
</div></form>';


$additionalMeta.='
	
	var vSlideQuote = new Fx.Slide(\'submitQuote\');

	vSlideQuote.hide();

	$(\'loadQuoteForm\').addEvent(\'click\', function(e){
		e.stop();
		vSlideQuote.slideIn();
	});
';

}

elseif($approved_tradesman == 1 && $tradesman_quoted != 1 && $same_tradesman != 1 && !$in_tradesmans_area){

$job_quotes.='<a style="cursor: pointer; text-decoration: underline;" class="blue_link" href="/my-subscription?upgrade=true">Submit quote</a>';

}

else{
// do nothing

}

// questions and answers

$questions_content = '<h2 id="questions_from_tradesmen_header">Questions from tradesmen</h2>';

$sql = "SELECT questions.id, question, answer, username, company_name, tradesman.id AS tradesman_id 
	FROM questions 
	LEFT JOIN tradesman ON questions.tradesman_id = tradesman.id 
	LEFT JOIN answers ON questions.id = answers.question_id 
	WHERE job_id = '".mysql_real_escape_string($_GET['id'])."' ORDER BY questions.id";
$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
$rows = mysql_num_rows($query);

if($approved_tradesman == 1 && $same_tradesman != 1 && $job_rs['job_status'] == 'Open' && $in_tradesmans_area){

$questions_content.= '<form method="post" action="/post_question.php"><input type="hidden" name="jid" value="'.$_GET['id'].'" /><div><a style="cursor: pointer; text-decoration: underline;" id="loadQuestionForm" class="blue_link" onclick="document.getElementById(\'question\').focus();">Ask a question</a></div>
<div id="askQuestion" style="float: left; width: 100%; padding-top: 5px;">
<div style="float: left; width: 80px; display: block;"><label for="question" style="font-size: 0.6875em;">Question:</label></div><div style="float: left; width: 250px;"><textarea name="question" id="question" rows="4" cols="30" style="float: left; width: 250px;"></textarea><input type="image" src="/images/ask_question.gif" alt="Ask question" style="margin-top: 5px; margin-left: 160px; display: inline;" /></div>
</div></form>';

$additionalMeta.='
	
	var vSlide = new Fx.Slide(\'askQuestion\');

	vSlide.hide();

	$(\'loadQuestionForm\').addEvent(\'click\', function(e){
		e.stop();
		vSlide.slideIn();
	});
';

}

if($rows > 0){

$i = 1;

while($question_rs=mysql_fetch_assoc($query)){

$tradesman_link = build_tradesman_link($question_rs['company_name'], $question_rs['tradesman_id']);

$questions_content.='<div class="question_container"><p><strong class="blue_colour">Question from: <a href="'.$tradesman_link.'">'.ucfirst($question_rs['company_name']).'</a></strong></p><p style="padding-top: 0;">'.ucfirst($question_rs['question']).'</p>';

if(strlen($question_rs['answer']) > 0){

$questions_content.='<p><strong class="blue_colour">Answer</strong></p><p style="padding-top: 0;">'.ucfirst($question_rs['answer']).'</p>';

}

else{

if($user_session[0] == $job_rs['user_id']){

$questions_content.='<form method="post" action="/post_answer.php"><div><a style="cursor: pointer; text-decoration: underline;" id="loadAnswerForm_'.$i.'" class="blue_link" onclick="document.getElementById(\'answer_'.$i.'\').focus();">Submit answer</a></div>
<input type="hidden" name="qid" value="'.$question_rs['id'].'" />
<div id="submitAnswer_'.$i.'" style="float: left; width: 100%; padding-top: 5px;">
<div style="float: left; width: 80px; display: block;"><label for="answer_'.$i.'" style="font-size: 0.6875em;">Answer:</label></div><div style="float: left; width: 250px;"><textarea name="answer" id="answer_'.$i.'" rows="4" cols="30" style="float: left; width: 250px;"></textarea><input type="image" src="/images/submit_answer.gif" alt="Submit answer" style="margin-top: 5px; margin-left: 150px; display: inline;" /></div>
</div></form>

';

$additionalMeta.='
	var vSlide_'.$i.' = new Fx.Slide(\'submitAnswer_'.$i.'\');

	vSlide_'.$i.'.hide();

	$(\'loadAnswerForm_'.$i.'\').addEvent(\'click\', function(e){
		e.stop();
		vSlide_'.$i.'.slideIn();
	});
';

}

}

$questions_content.='</div>';

$questions_content.=($i != $rows)?'<div class="divider"><hr /></div>':'';

$i++;

}

}

else{

$questions_content.= '<p>There are currently no questions for this job.</p>';

}


// messages and replies

$sql = "SELECT messages.id, message, reply, messages.tradesman_id, username, tradesman.user_id AS tradesmans_user_id, tradesman.company_name FROM messages 
	LEFT JOIN replies ON messages.id = replies.message_id 
	LEFT JOIN tradesman ON messages.tradesman_id = tradesman.id 
	WHERE job_id = '".mysql_real_escape_string($_GET['id'])."' ORDER BY message_date DESC";
$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
$rows = mysql_num_rows($query);

if($rows > 0){

$i = 1;

while($message_rs=mysql_fetch_assoc($query)){

if($message_rs['tradesmans_user_id'] == $user_session[0] || $user_session[0] == $job_rs['user_id']){

$tradesman_link = build_tradesman_link($message_rs['company_name'], $message_rs['tradesman_id']);

$messages_content.='<div class="question_container"><p><strong class="blue_colour">Message for: <a href="'.$tradesman_link.'">'.ucfirst($message_rs['company_name']).'</a></strong></p><p style="padding-top: 0;">'.ucfirst($message_rs['message']).'</p>';

if(strlen($message_rs['reply']) > 0){

$messages_content.='<p><strong class="blue_colour">Reply</strong></p><p style="padding-top: 0;">'.ucfirst($message_rs['reply']).'</p>';

}

else{

if($message_rs['tradesmans_user_id'] == $user_session[0]){

$messages_content.='<form method="post" action="/post_reply.php"><div><a style="cursor: pointer; text-decoration: underline;" id="loadReplyForm_'.$i.'" class="blue_link" onclick="document.getElementById(\'reply_'.$i.'\').focus();">Submit reply</a></div>
<input type="hidden" name="mid" value="'.$message_rs['id'].'" />
<div id="submitReply_'.$i.'" style="float: left; width: 100%; padding-top: 5px;">
<div style="float: left; width: 80px; display: block;"><label for="reply_'.$i.'" style="font-size: 0.6875em;">Reply:</label></div><div style="float: left; width: 250px;"><textarea name="reply" id="reply_'.$i.'" rows="4" cols="30" style="float: left; width: 250px;"></textarea><input type="image" src="/images/submit_reply.gif" alt="Submit reply" style="margin-top: 5px; margin-left: 150px; display: inline;" /></div>
</div></form>

';

$additionalMeta.='
	var rSlide_'.$i.' = new Fx.Slide(\'submitReply_'.$i.'\');

	rSlide_'.$i.'.hide();

	$(\'loadReplyForm_'.$i.'\').addEvent(\'click\', function(e){
		e.stop();
		rSlide_'.$i.'.slideIn();
	});
';

}

}

$messages_content.= '</div>';

$messages_content.=($i != $rows)?'<div class="divider"><hr /></div>':'';

$i++;

}

}

}

if(strlen($messages_content) > 0){

$messages_content = '<h2 id="questions_from_user_header">Questions from user</h2>'.$messages_content;

}

$additionalMeta.='});
</script>';

// visit requests

if($user_session[0] == $job_rs['user_id'] && $job_rs['job_status'] == 'Open'){

	$visits_content = '<h2>Visit requests</h2>';

	$sql = "SELECT visit_requests.id, visit_requests.accepted, visit_requests.tradesman_id, company_name FROM visit_requests 
			LEFT JOIN tradesman ON visit_requests.tradesman_id = tradesman.id 
			WHERE visit_requests.job_id = '".mysql_real_escape_string($_GET['id'])."'";
	$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
	$rows = mysql_num_rows($query);

	if($rows > 0){
	
	$visits_content.='<p>The following tradesmen have requested to visit your property in order to help them with your quote. Only accept if you\'re happy for them to contact you and visit your property.</p>';

	$i = 1;
	
	$visits_content.='<table width="100%" class="standard">';

		while($visit_rs=mysql_fetch_assoc($query)){
		
		$highlight = (is_int($i / 2)) ? ' class="highlight"' : '';
		
		$tradesman_link = build_tradesman_link($visit_rs['company_name'], $visit_rs['tradesman_id']);
		$approved = ($visit_rs['accepted'] == '1') ? 'Accepted' : '<a href="?accept_request='.$visit_rs['id'].'">Accept</a>' ;
		
		$visits_content.='<tr'.$highlight.'><td class="alignLeft"><a href="'.$tradesman_link.'">'.$visit_rs['company_name'].'</a></td><td style="text-align: right;">'.$approved.'</td></tr>';
		
		$i++;
		
		}
		
	$visits_content.='</table>';
	
	}
	
	else{
	
	$visits_content.='<p>You have not received any visit requests.</p>';
	
	}

}

// lead purchases

if($user_session[0] == $job_rs['user_id'] && $job_rs['job_status'] == 'Open'){

	$visits_content.= '<h2>Details requests</h2>';

	$sql = "SELECT lead_purchases.id, lead_purchases.accepted, lead_purchases.declined, lead_purchases.tradesman_id, company_name FROM lead_purchases 
			LEFT JOIN tradesman ON lead_purchases.tradesman_id = tradesman.id 
			WHERE lead_purchases.job_id = '".mysql_real_escape_string($_GET['id'])."'";
	$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
	$rows = mysql_num_rows($query);

	if($rows > 0){
	
	$visits_content.='<p>The following tradesmen have requested to view your contact details, so that they can contact you regarding your job. Only accept if you\'re happy for them to contact you.</p>';

	$i = 1;
	
	$visits_content.='<table width="100%" class="standard">';

		while($visit_rs=mysql_fetch_assoc($query)){
		
		$highlight = (is_int($i / 2)) ? ' class="highlight"' : '';
		
		$tradesman_link = build_tradesman_link($visit_rs['company_name'], $visit_rs['tradesman_id']);
		
		if($visit_rs['accepted'] == '1' || $visit_rs['declined'] == '1'){
		$approved = ($visit_rs['accepted'] == '1') ? '<td colspan="2" style="text-align: right;">Accepted</td>' : '<td colspan="2" style="text-align: right;">Declined</td>' ;
		}
		
		else{
		$approved = '<td style="text-align: right;"><a href="?accept_details_request='.$visit_rs['id'].'">Accept</a></td><td style="text-align: right;"><a href="?decline_details_request='.$visit_rs['id'].'">Decline</a></td>' ;
		}
		
		
		$visits_content.='<tr'.$highlight.'><td class="alignLeft"><a href="'.$tradesman_link.'">'.$visit_rs['company_name'].'</a></td>'.$approved.'</tr>';
		
		$i++;
		
		}
		
	$visits_content.='</table>';
	
	}
	
	else{
	
	$visits_content.='<p>You have not received any details requests.</p>';
	
	}

}


if($user_session[0] == $job_rs['user_id'] && $job_rs['job_status'] == 'Open'){
$cancel_link = '<br /><a href="/cancel_job.php?id='.$_GET['id'].'" class="blue_link" style="color: #ffffff; margin-top: 10px;">Cancel this job</a>';

	if($img_rows < 3){
	
	$new_id = $img_rows + 1;

	$image_form = '
	<h2 id="show_image_form" style="text-decoration: underline; cursor: pointer;">Add images</h2>
	<div id="image_upload" style="float: left; width: 100%; display: none;">
	<form method="post" enctype="multipart/form-data" id="image_upload">
	<input type="hidden" name="total_images" id="total_images" value="1" style="display: none;" />
	<div class="rowWrapper" id="image_wrap">
	<div class="rowLeft"><label for="image_1">Images:</label><br /><span>(2mb Max)</span></div>
	<div class="rowRight">
	<div id="image_uploads">
	<div class="image_upload_container"><input type="file" name="image_1" id="image_1" class="textbox" /></div>
	</div>';
	$image_form.= ($img_rows < 2) ? '<div id="addImageLink"><a onclick="return addImageInput('.$new_id.');" style="font-size: 12px;">Add another</a></div>' : '';
	
	$image_form.= '</div>
	</div>
	<a onclick="document.forms[\'image_upload\'].submit();" class="blue_link">Upload images</a>
	</form>
	</div>
	';
	
	}

}

$result = (strlen($_GET['result']) > 0) ? '<p style="color: #009900; position: relative; top: -4px; padding-top: 0px; margin-top: 0px;"><strong>Your '.$_GET['result'].' has been submitted!</strong></p>' : '';

$materials = ($rs['materials'] == '1') ? 'Yes' : 'No' ;

$content='
<h2 id="job_title">'.ucfirst($job_rs['title']).'</h2>
<div id="job_info">'.$result.ucfirst(str_replace("\r\n", "<br /><br />", $job_rs['description'])).'<div class="divider"><hr /></div>
<div id="job_images" style="margin-top: 20px;">
'.$job_images.'
</div>
'.$image_form.'
<p style="font-size: 12px;"><strong class="blue_colour">Customer providing materials: '.$materials.'<br />Job status: <span class="job'.$job_rs['job_status'].'">'.$job_rs['job_status'].'</span></strong>'.$cancel_link.'</p>
'.$user_contact_details.'
</div>
<div id="job_map"></div>
<div class="divider"><hr /></div>
<div style="clear:both"></div>
'.$job_quotes.'
<div style="clear:both; height: 10px;"></div>
'.$questions_content.'
<div class="divider"><hr /></div>
'.$messages_content.'
'.$visits_content.'
';

if($job_rs['latitude'] == 0){

$sql = "SELECT longitude, latitude
	FROM areas 
	WHERE id = '".$job_rs['area_id']."' LIMIT 0,1";
$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
$coords_rs=mysql_fetch_assoc($query);

$job_rs['latitude'] = $coords_rs['latitude'];
$job_rs['longitude'] = $coords_rs['longitude'];

}

$additionalMeta.='
<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key='.$settings['google_api_key'].'&amp;sensor=false" type="text/javascript"></script>
<script type="text/javascript">
function initialize(){
	if (GBrowserIsCompatible()) {
        var map = new GMap2(document.getElementById("job_map"));
        map.setCenter(new GLatLng('.$job_rs['latitude'].', '.$job_rs['longitude'].'), 9);
        var marker = new GMarker(new GLatLng('.$job_rs['latitude'].', '.$job_rs['longitude'].'));
        map.addOverlay(marker);
	}
}
</script>';

$bodyTag = ' onload="initialize()" onunload="GUnload()"';

$page_title = htmlentities($job_rs['trade']).' wanted - '.htmlentities($job_rs['area']);

include('includes/meta.php');
include('includes/header.php');
include('includes/navigation.php');

?>

<h1><?php echo $page_title; ?></h1>

<?php echo $content; ?>

<?php

include('includes/rightColumn.php');
include('includes/footer.php');

?>